package com.pet.server.ext.action.square;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONObject;

import com.pet.server.ext.ActionBase;
import com.pet.server.ext.ApiError;
import com.pet.server.ext.Result;
import com.pet.server.ext.constants.BaseAttribute;
import com.pet.server.ext.data.Image;
import com.pet.server.ext.data.PetAdopt;
import com.pet.server.ext.data.PetMissing;
import com.pet.server.ext.service.UserService;
import com.pet.server.ext.util.DateUtil;
import com.pet.server.ext.util.Parameters;
import com.pet.server.ext.util.StringUtil;

public class Adoptpublish extends ActionBase{
	private PetAdopt petAdopt;
	private List<String> images;
	
	public Adoptpublish(){
		 needCheckAuth =true;
	}
	
	@Override
	public void initParameters(Parameters params) throws ApiError {	
		images=new ArrayList<String>();
		petAdopt = new PetAdopt();
		petAdopt.area=StringUtil.dealNull(params.getFieldValue("area"));
		petAdopt.age=StringUtil.dealNull(params.getFieldValue("age"));
		petAdopt.breed=StringUtil.dealNull(params.getFieldValue("breed"));
		petAdopt.description=StringUtil.dealNull(params.getFieldValue("description"));
		petAdopt.pet_cate=StringUtil.dealNull(params.getFieldValue("pet_cate"));
		petAdopt.sex=StringUtil.dealNull(params.getFieldValue("sex"));
		petAdopt.qq=StringUtil.dealNull(params.getFieldValue("qq"));
		petAdopt.phone=StringUtil.dealNull(params.getFieldValue("phone"));
		petAdopt.city=StringUtil.dealNull(params.getFieldValue("city"));
		petAdopt.is_birth=BaseAttribute.LOGIC_TRUE.equals(params.getFieldValue("is_birth"))?BaseAttribute.LOGIC_TRUE:BaseAttribute.LOGIC_FALSE;
		petAdopt.is_injection=BaseAttribute.LOGIC_TRUE.equals(params.getFieldValue("is_injection"))?BaseAttribute.LOGIC_TRUE:BaseAttribute.LOGIC_FALSE;
		int i=0;
		while(params.getFileUrl("image"+i)!=null){
			images.add(params.getFileUrl("image"+i));
			i++;
		}
		if(images.size()>0){
			petAdopt.ico_path=images.get(0);
		}
		
        if(StringUtil.isEmpty(petAdopt.pet_cate,petAdopt.breed)){
        	throw ApiError.Type.INVALID_PARAM.toException();
        }
	}
	@Override
	public Result invokeService() throws ApiError {
		UserService userService = new UserService();
		petAdopt.user_id=user.user_id;
		userService.savePetAdopt(petAdopt);
		JSONObject data = new JSONObject();
		for(String image:images){
			Image img = new Image();
			img.type=BaseAttribute.image_type.pet_adopt.toString();
			img.src=image;
			img.oid=petAdopt.adopt_id;
			userService.saveImage(img);
		}
		data.accumulate("message", "添加信息成功!");
		
		Result result = new Result();
		result.put("data", data);
	    return result;
	}


}
